<template>
    <div class="app-container">
        <div class="flex-head">
            <FormSearch
                ref="formSearchRef"
                :FormParams="queryParams"
                :FormRules="searchFormRules"
                :FormShow="showSearch"
                @submit="getList"
                @refresh="getList" />
            <el-row class="mb20">
                <el-col :span="20">
                    <el-button type="primary" @click="uploadExcel" icon="Upload">上传文件</el-button>
                    <!-- <el-button type="danger" :disabled="disabled" icon="Delete" @click="handleBatchDelete">批量删除</el-button> -->
                </el-col>
                <el-col :span="4">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
                </el-col>
            </el-row>
        </div>
        <TableBate
            id="tableBateId"
            ref="tableRef"
            :loading="loading"
            :TableHead="tableHead"
            :TableData="tableData"
            :TableAttrs="tableAttrs"
            @handleSelectionChange="handleSelectionChange"
            @handleActionBarEvent="handleActionBarEvent">
            <template #name="{ row }">
                <span>{{ row.touristList.map((item) => item.name).join('、') }}</span>
            </template>
            <template #status="{ row }">
                <template v-for="item in statusOptions">
                    <el-tag v-if="item.value == row.status" :type="item.elTagClass">{{ item.label }}</el-tag>
                </template>
            </template>
            <template #image="{ row }">
                <div>
                    <img v-if="row.payUrl" width="150" height="150" :src="row.payUrl" />
                    <div v-else></div>
                </div>
            </template>
        </TableBate>
        <pagination
            id="pagination"
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNumber"
            v-model:limit="queryParams.pageSize"
            @pagination="getList" />
        <el-dialog v-model="uploadDialog" title="上传文件" width="30vw" center>
            <div>
                <input 
                    ref="iptFile"
                    type="file" 
                    accept=".txt"
                    @change="handleFileChange($event)"
                >
            </div>
            <div class="wrap-button">
                <el-button @click="fileCancel">取消</el-button>
                <el-button @click="fileSubmit" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import FormSearch from '@/components/FormSearch/index.jsx'
import TableBate from '@/components/Table_Bate/index.jsx'
import { ElMessage, ElMessageBox } from 'element-plus'
import { searchFormRules, tableHead, statusOptions } from './config'
import { onMounted, reactive, toRefs, getCurrentInstance, watch } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { orderPages, batchCreate, orderUserPages } from '@/api/ppmt/index'
import { projectList } from '@/api/project/item'

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

const formSearchRef = ref()
// 右侧工具栏是否显示
const showSearch = ref(true)
// 列表数据
const tableData = ref([])
const tableRef = ref()
const loading = ref(false)
const uploadDialog = ref(false)
const multipleSelection = ref([])
const disabled = ref(true)
const total = ref(0)
const timer = ref()
const textFileData = ref([])
const iptFile = ref()

const data = reactive({
    queryParams: {
        pageNumber: 1,
        pageSize: 10,
    },
    tableAttrs: {
        size: 'large',
        align: 'center',
    },
})

const { queryParams, tableAttrs } = toRefs(data)

watch(
    multipleSelection,
    (newMultipleSelection) => {
        disabled.value = !newMultipleSelection.length
    },
    { deep: true },
)

const fileCancel = () => {
    textFileData.value = []
    uploadDialog.value = false
    iptFile.value.value = ''
    console.log(iptFile.value.value, 'iptFile.value.value');
    
}

// 提交上传文件到数据
const fileSubmit = () => {
    batchCreate({deviceIdList: textFileData.value}).then(res => {
        proxy.$modal.msgSuccess('上传数据成功')
        fileCancel()
        getList()
    })
}


// 获取上传到txt文件数据
const handleFileChange = (event) => {
    const reader = new FileReader()
    reader.readAsText(event.target.files[0], "utf-8")
    reader.onload = function () {
        textFileData.value = reader.result.split('\n'), "reader.result.split('\n')"
        console.log(textFileData.value, 'textFileData.value');
        
    };
}

// 定时请求
const timingRequest = () => {
    timer.value = setInterval(() => {
        getList()
    }, 12000)
}

//批量删除
// const handleBatchDelete = () => {
//     const userIds = multipleSelection.value.map((item) => item.touristList.map((user) => user.id))
//     handleDelete(userIds.flat())
// }

// 已选中的行数据
const handleSelectionChange = (data) => {
    multipleSelection.value = data
}

// 搜索
const searchFormSubmit = (data) => {
    for (let key in data) {
        if (data[key]) {
            queryParams.value[key] = data[key]
        }
    }
    queryParams.value
    getList()
}

// 重置
const handleRefresh = () => {}

// 获取table数据
const getList = () => {
    loading.value = true
    orderUserPages(queryParams.value).then(({ result: res }) => {
        tableData.value = res.data
        total.value = res.total
        loading.value = false
    })
}

// 上传表格
const uploadExcel = () => {
    uploadDialog.value = true
}

/**
 * 自适应
 * @param el
 */
const adaptiveResize = (el) => {
    const resizeObserver = new ResizeObserver((entries) => {
        debouncedFn(entries[0].contentRect)
    })
    resizeObserver.observe(el)
}

const debouncedFn = useDebounceFn((elContentRect) => {
    tableAttrs.value.height = elContentRect.height + 'px'
}, 100)

// 删除单个
const handleSingleDelete = (row) => {
    const ids = row.touristList.map((item) => item.id)
    handleDelete(ids)
}
const handleDelete = (ids) => {
    ElMessageBox.confirm(`确认要删除ID为${ids.join('、')}的数据项?`, '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            touristTicketDelete(ids).then((res) => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getList()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: `取消删除`,
            })
        })
}
const handleActionBarEvent = (row, type) => {
    if (type === '删除') {
        handleSingleDelete(row)
    }
}
</script>

<style lang="scss" scoped>
.wrap-button {
    width: 100%;
    display: block;
    margin-top: 12px;
    text-align: right
}
</style>